package com.lmsservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lmsservice.common.R;
import com.lmsservice.entity.Book;
import com.lmsservice.entity.BookType;
import com.lmsservice.service.BookService;
import com.lmsservice.service.BookTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/booktype")
public class BookTypeController {

    @Autowired
    private BookTypeService bookTypeService;


    @Autowired
    private BookService bookService;

    @GetMapping
    public R<List<BookType>> getlist(){
        List<BookType> list = bookTypeService.list();
        return R.success(list);
    }

    @GetMapping("/page")
    public R<Page> getPage(Integer page , Integer pageSize){
        Page<BookType> page1 = new Page<>(page , pageSize);
        bookTypeService.page(page1);
        return R.success(page1);
    }

    @PutMapping
    public R<String> update(@RequestBody BookType bookType){
        bookTypeService.updateById(bookType);
        return R.success("修改成功");
    }

    @DeleteMapping
    public R<String> delete(@RequestBody BookType bookType){

        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(bookType.getId()!=null,Book::getType,bookType.getId());
        Book book = bookService.getOne(queryWrapper);
        if (book!=null){
            return R.error("删除失败，存在该类型书籍");
        }
        bookTypeService.removeById(bookType);
        return R.success("删除成功");
    }

    @PostMapping
    public R<String> add(@RequestBody BookType bookType){

        LambdaQueryWrapper<BookType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(bookType.getName()!=null,BookType::getName,bookType.getName());
        BookType bookType1 = bookTypeService.getOne(queryWrapper);
        if (bookType1!=null){
            return R.error("该类型已存在");
        }

        bookTypeService.save(bookType);
        return R.success("添加成功");
    }
}
